import json
import os
from datetime import datetime
from langchain_core.messages import HumanMessage, AIMessage, ChatMessage
from . import prompt_config
params = prompt_config.PromptConfig()


def save_conversation_history(memory, file_path=params.save_conversation_history):
    """
    将内存中对话记录存入指定文件路径下
    :param memory:记忆对象
    :return:
    """
    for message in chat_history:
        if isinstance(message, HumanMessage):
            msg_type = "human"
        elif isinstance(message, AIMessage):
            msg_type = "ai"
        elif isinstance(message, ChatMessage):
            # 自定义角色消息：直接使用其role属性作为类型（如"牛爷爷"）
            msg_type = message.role
        else:
            msg_type = "unknown"

        serializable_history.append({
            "type": msg_type,
            "content": message.content,
            "timestamp": datetime.now().isoformat()
        })

    with open(file_path, "w", encoding="utf-8") as f:
        json.dump(serializable_history, f, ensure_ascii=False, indent=2)

    print(f"对话历史已保存到 {file_path}")


def load_conversation_history(memory, file_path=params.load_conversation_history):
    """从JSON文件加载对话历史"""
    if not os.path.exists(file_path):
        print(f"未找到对话历史文件 {file_path}，将开始新对话")
        return

    try:
        with open(file_path, "r", encoding="utf-8") as f:
            history = json.load(f)
        memory.clear()

        # 该循环不读入识别为"unknown"的信息
        for msg in history:
            if msg["type"] == "human":
                memory.chat_memory.add_user_message(msg["content"])
            elif msg["type"] == "ai":
                memory.chat_memory.add_ai_message(msg["content"])
            

        print(f"已从 {file_path} 加载 {len(history)} 条对话历史")
    except Exception as e:
        print(f"加载对话历史失败: {str(e)}")

# if __name__ == "__main__":
#     load_conversation_history(memory, history_file)
